#include "jeremy.h"

/* Vrati pocet nastaveni ve stromu */
int num_settings(struct settings * tree)
{
	int n;
	
	/* Prohledavame strom, dokud nenarazime na null odkaz na dalsi prvek */
	for(n = 0; tree->next_settings != NULL; n++) {
		tree = tree->next_settings;
	}

	return n;
}

/* Prida novou polozku do stromu s nastavenim */
int add_settings(struct settings * tree, char * name, char * value)
{
	/* Posunuti na konec stromu */
	while(tree->next_settings != NULL) {
		tree = tree->next_settings;
	}

	/* Alokovani pameti pro ulozeni jmena a hodnoty */
	tree->name = (char *) malloc(strlen(name) + 1);
	if (tree->name == NULL) death(ERR_MEM, __func__);
	tree->value = (char *) malloc(strlen(value) + 1);
	if (tree->value == NULL) death(ERR_MEM, __func__);

	strcpy(tree->name, name);
	strcpy(tree->value, value);

	/* Alokujeme misto pro dalsi polozku v seznamu */
	tree->next_settings = (struct settings *) malloc(sizeof(struct settings));
	if (tree->next_settings == NULL) {
		death(ERR_MEM, __func__);
	}
	tree->next_settings->next_settings = NULL;

	return true;
}

/* Vraci strukturu settings daneho jmena ze stromu s nastavenim 
 * Pokud nebyla struktura nalezena, vraci NULL */
struct settings * get_settings(struct settings * tree, char * name)
{
	if (DEBUG == true) {
		printf("Hledame v nastaveni\n");
	}

	while(tree->next_settings != NULL) {

		if (DEBUG == true) {
			printf("%s = %s\n", tree->name, tree->value);
		}

		/* Porovname nazev hodnoty */
		if (strncmp(name, tree->name, strlen(name)) == 0) {

			if (DEBUG == true) {
				printf("Uspesne nalezeno: %s\n", name);
			}
			
			/* Vracime aktualni strukturu */
			return tree;
		}

		/* Posuneme se na dalsi hodnotu */
		tree = tree->next_settings;
		if (DEBUG == true) {
			printf("Posunuto.\n");
		}
	}

	return NULL;
}

/* Parser konfiguracniho souboru
 * Vraci true v pripade uspechu, jinak false */
int conf_file_parser(struct settings * tree, char file[])
{
	FILE * fp;
	char buf[1024];
	char * w1;
	char * w2;

	fp = fopen(file, "r");
	if (!fp) return false;

	while (fgets(buf, sizeof(buf), fp) != NULL) {
		if(buf[0] == '#' || buf[0] == '\r' || buf[0] == '\n') continue;
		
		buf[strlen(buf) - 1] = '\0';
		w1 = strtok(buf, " ");
		w2 = strtok(NULL, " ");

		if (DEBUG == true) { 
			printf("Polozka konfigurace: %s = %s\n", w1, w2);
		}

		add_settings(tree, w1, w2);
		
		if (DEBUG == true) {
			puts("Uspesne vlozena");
		}

	}

	return true;
}
